//
//  LQRefreshControl.swift
//  Weibo
//
//  Created by ios on 16/8/14.
//  Copyright © 2016年 ios. All rights reserved.

import UIKit
//  当前视图的高度
private let LQRefreshControlHeight: CGFloat = 50

//  刷新状态

enum CZRefreshControlType: Int {
    //  下拉刷新
    case Normal = 0
    //  将要刷新
    case Pulling = 1
    //  正在刷新
    case Refreshing = 2
    
}

class LQRefreshControl: UIControl {
    
    //  当前滚动的视图
    var currentScrollView: UIScrollView?
    
    //当前的状态
    var refreshState: CZRefreshControlType = .Normal{
        didSet{
            switch refreshState {
            case .Normal:
                //  显示文字为下拉刷新
                messageLabel.text = "下拉刷新"
                //  风火轮停止
                indicatorView.stopAnimating()
                //  箭头显示，箭头重置
                iconImageView.hidden = false
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconImageView.transform = CGAffineTransformIdentity
                })
                
                //刷新完后回到默认位置
                if oldValue == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.currentScrollView?.contentInset.top -= LQRefreshControlHeight
                    })
                }
            case .Pulling:
                  //  显示文字为松手就刷新
                messageLabel.text = "松手就刷新"
                 // 箭头掉置
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            case .Refreshing:
                //显示文字为正在刷新
                messageLabel.text = "正在刷新"
                //  风火轮开启 隐藏剪头
                indicatorView.startAnimating()
                iconImageView.hidden = true
                //设置停留位置
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.currentScrollView?.contentInset.top += LQRefreshControlHeight
                })
                // 发送通知(一定要记住)
                sendActionsForControlEvents(.ValueChanged)
            
            }
        
        }
    
    }
    
    // MARK:    --懒加载控件
    private lazy var iconImageView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //  风火轮
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    //  显示文案
    private lazy var messageLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(12)
        label.textColor = UIColor.grayColor()
        label.text = "下拉刷新"
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  添加控件 设置约束
    private func setupUI() {
        //  暂时写死
        //        width = ScreenWidth
        //        height = 50
        //        y = -50
        backgroundColor = UIColor.redColor()
        
        //  添加控件
        addSubview(iconImageView)
        addSubview(indicatorView)
        addSubview(messageLabel)
        
        
        //  使用系统约束
        iconImageView.translatesAutoresizingMaskIntoConstraints = false
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: NSLayoutAttribute.CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: NSLayoutAttribute.CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: NSLayoutAttribute.CenterX, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: NSLayoutAttribute.CenterY, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.Leading, relatedBy: .Equal, toItem: iconImageView, attribute: .Trailing, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .CenterY, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterY, multiplier: 1, constant: 0))
    }
    //  监听tableview的滚动,拿到tableview, 将控件将要添加到那个父亲视图上
    override func willMoveToSuperview(newSuperview: UIView?) {
          //  判断父视图是否是可以滚动的视图
        guard let scrollview = newSuperview as? UIScrollView else {
          return
        }
        //代码执行到此 证明视图为滚动的视图
        
        //设置当前视图的frame
        self.frame.size.width = scrollview.frame.size.width
        self.frame.size.height = LQRefreshControlHeight
        self.frame.origin.y = -LQRefreshControlHeight
        //  kvo监听滚动对象contentOffSet属性的改变
        //  监听contentOffset新值的改变
        scrollview.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        
        //  记录滚动的视图
        currentScrollView = scrollview
    }
    
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        //判断当前视图是否存在
        guard let  scrollView = currentScrollView else {
           return
        }
        //  获取滚动的y轴的偏移量
        let contentOffSetY = scrollView.contentOffset.y
        
        //计算临界点
        
        let maxY = -(scrollView.contentInset.top + LQRefreshControlHeight)
        
        //判断是否被拖动
        if scrollView.dragging {
            if contentOffSetY < maxY && refreshState == .Normal {
                //松手就刷新
              refreshState = .Pulling
            } else if contentOffSetY > maxY && refreshState == .Pulling{
                 //下拉刷新
               refreshState = .Normal
            }
        
        }else{
            //  判断是否进入正在刷新的状态
            if refreshState == .Pulling{
                //刷新状态
              refreshState = .Refreshing
            }
        
        }
        
    }
    
    //结束刷新
    func endRefreshing() {
        //  进入默认状态
        refreshState = .Normal
    }
    deinit{
      //移除kvo
        currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }

}
